#!/usr/bin/env python
import os
from gtk import *
from xmmsclient import *
import xmmsclient.glib

class Player(VBox):
    duration = 0
    progress_bar_pressed = False
    
    def __init__(self, xmms2):
        VBox.__init__(self)
        self.xmms2 = xmms2
        self.progress_bar = HScale()
        self.pack_start(self.progress_bar, expand=False)
        self.progress_bar.connect("button-press-event", 
            self.on_progress_bar_pressed)
        self.progress_bar.connect("button-release-event", 
            self.on_progress_bar_released)
        self.xmms2.playback_current_id(cb=self.on_current_id_changed)
        self.xmms2.broadcast_playback_current_id(self.on_current_id_changed)
        self.xmms2.signal_playback_playtime(self.update_playtime)
            
    def on_progress_bar_pressed(self, *args):
        self.progress_bar_pressed = True
        
    def on_progress_bar_released(self, *args):
        self.progress_bar_pressed = False
        playtime = self.progress_bar.get_value()
        self.xmms2.playback_seek_ms(playtime)
            
    def get_playtime(self, res):
        if res.iserror():
            print "get_playtime error"
            return
        tag = res.value()
        self.duration = tag["duration"]
        self.progress_bar.set_range(0, self.duration)
        
    def on_current_id_changed(self, res):
        if res.iserror():
            print "error broadcasting current id"
            return
        id = res.value()
        self.xmms2.medialib_get_info(id, cb=self.get_playtime)
        
    def update_playtime(self, res):
        if res.iserror():
            print "could not update playtime"
            res.restart()
            return
        elif self.progress_bar_pressed:
            res.restart()
            return
        playtime = res.value()
        self.progress_bar.set_value(playtime)
        res.restart()
        
    def play(self, *args):
        self.xmms2.playback_start()
        
    def pause(self, *args):
        self.xmms2.playback_pause()
        
    def stop(self, *args):
        self.xmms2.playback_stop()
        
    def next(self, *args):
        self.xmms2.playlist_set_next_rel(1)
        self.xmms2.playback_tickle()
        
    def previous(self, *args):
        self.xmms2.playlist_set_next_rel(-1)
        self.xmms2.playback_tickle()


        
if __name__ == "__main__":
    xmms2 = XMMS("player_manager")

    try:
        xmms2.connect(os.getenv("XMMS_PATH"))
    except Exception, e:
        print "could not connect", e
        exit(1)

    xmmsclient.glib.GLibConnector(xmms2)
    pl = Player(xmms2)

    w = Window()
    w.connect("delete-event", lambda *args: main_quit())
    w.add(pl)
    w.show_all()

    main()
